<?php

$html = '<div class="pageName"><h2>Книги</h2></div>';
$html_search_sort = '<div class="searchSort">
    <div class="sort">
        <form method="GET" action="index.php">
            <select name="sort_column">
                <option value="book_title">Книги</option>
                <option value="author_name">Автори</option>
            </select>
            <input id="ascending" type="radio" value="asc" name ="order">
            <label for="ascending">Възходящо</label>
            <input id="descending" type="radio" value="desc" name="order">
            <label for="descending">Низходящо</label>
            <input type="submit" value="Сортирай">
        </form>
    </div>
    <div class="search">
        <form method="GET"  action="index.php">
            <input type="text" name="search">
            <input type="submit" value="Търси">
        </form>
    </div>
</div>';

if (count($data['books']) > 0) {
    $html .= $html_search_sort;
    $html .= '<div class="booksResults"><table><thead><tr>' .
            '<th class="thBooks">Книги</th><th class="thAuthors">Автори</th><th id="thComments">Коментари</th>' .
            '</tr></thead><tbody>';
    $oddEven = 'odd';
    foreach ($data['books'] as $value) {
        if ($oddEven == 'odd') {
            $oddEven = 'even';
        } else {
            $oddEven = 'odd';
        }
        $html .= '<tr class="' . $oddEven . '"><td><a href="index.php?p=book&book_id=' .
                $value['book_id'] . '">' . htmlspecialchars($value['book_title']) . '</a></td><td>';
        $authors = array();
        foreach ($value['authors'] as $author) {
            $authors[] = '<a href="index.php?p=author&author_id='
                    . $author['id'] . '">'
                    . htmlspecialchars($author['name']) . '</a>';
        }
        $html .= implode(', ', $authors);
        $html .= '</td><td class="commentsCell">' . $value['commentsCount'] . '</td></tr>';
    }
    $html .= '</tbody></table></div>';
} else {
    if (isset($_GET['search'])) {
        $html .= '<p class="error">Нищо не е намерено</p>';
    }
}

echo $html;